package com.zztl.infiniteBand.storage

import android.content.Context
import android.content.SharedPreferences
import android.util.Base64
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.zztl.infiniteBand.util.UiUtils
import java.io.*
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Method
import java.util.*

/**
 * @desc
 * @auth ${user}
 * @time 2018/6/21  16:10
 */
object BillPreference {
    private var gson: Gson? = null

    /**
     * 返回所有的键值对
     */
    val all: Map<String, *>
        get() {
            val sp = UiUtils.context.getSharedPreferences("bill", Context.MODE_PRIVATE)
            return sp.all
        }

    /**
     * 保存数据的方法
     */
    fun putApp(key: String, `object`: Any) {

        val sp = UiUtils.context.getSharedPreferences("bill", Context.MODE_PRIVATE)
        val editor = sp.edit()

        if (`object` is String) {
            editor.putString(key, `object`)
        } else if (`object` is Int) {
            editor.putInt(key, `object`)
        } else if (`object` is Boolean) {
            editor.putBoolean(key, `object`)
        } else if (`object` is Float) {
            editor.putFloat(key, `object`)
        } else if (`object` is Long) {
            editor.putLong(key, `object`)
        } else {
            editor.putString(key, `object`.toString())
        }

        BillPreference.SharedPreferencesCompat.apply(editor)
    }

    /**
     * 得到保存数据的方法
     */
    fun getApp(key: String, defaultObject: Any): Any? {
        val sp = UiUtils.context.getSharedPreferences("bill", Context.MODE_PRIVATE)

        if (defaultObject is String) {
            return sp.getString(key, defaultObject)
        } else if (defaultObject is Int) {
            return sp.getInt(key, defaultObject)
        } else if (defaultObject is Boolean) {
            return sp.getBoolean(key, defaultObject)
        } else if (defaultObject is Float) {
            return sp.getFloat(key, defaultObject)
        } else if (defaultObject is Long) {
            return sp.getLong(key, defaultObject)
        }

        return null
    }


    /**
     * 保存对象
     *
     * @param
     * @param t
     * @param keyName
     * @param <T>
    </T> */
    fun <T> saveObj2SP(keyName: String, t: T) {
        val sp = UiUtils.context.getSharedPreferences("bill", Context.MODE_PRIVATE)

        val bos: ByteArrayOutputStream
        var oos: ObjectOutputStream? = null
        try {
            bos = ByteArrayOutputStream()
            oos = ObjectOutputStream(bos)
            oos.writeObject(t)
            val bytes = bos.toByteArray()
            // String ObjStr = new String(bytes,0,bytes.length);
            val ObjStr = String(Base64.encode(bytes, Base64.DEFAULT))
            val editor = sp.edit()
            editor.putString(keyName, ObjStr)
            BillPreference.SharedPreferencesCompat.apply(editor)
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            //关闭流
            if (oos != null) {
                try {
                    oos.flush()
                    oos.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }

            }
        }
    }


    /**
     * 从sp中读取对象
     *
     *
     * @param keyNme   字段名
     * @param <T>      泛型参数
     * @return
    </T> */
    fun <T : Any> getObjFromSp(keyNme: String): T? {
        val sp = UiUtils.context.getSharedPreferences("bill", Context.MODE_PRIVATE)
        val bytes = Base64.decode(sp.getString(keyNme, "")!!.toByteArray(), Base64.DEFAULT)
        var bis: ByteArrayInputStream? = null
        var ois: ObjectInputStream? = null
        var obj: T? = null
        try {
            bis = ByteArrayInputStream(bytes)
            ois = ObjectInputStream(bis)
            obj = ois.readObject() as T
        } catch (e: IOException) {
            e.printStackTrace()
        } catch (e: ClassNotFoundException) {
            e.printStackTrace()
        } finally {
            if (ois != null) {
                try {
                    bis!!.close()
                    ois.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }

            }
        }
        return obj
    }


    /**
     * 移除某个key值已经对应的值
     *
     * @param key
     */
    fun remove(key: String) {
        val sp = UiUtils.context.getSharedPreferences("bill", Context.MODE_PRIVATE)
        val editor = sp.edit()
        editor.remove(key)
        BillPreference.SharedPreferencesCompat.apply(editor)
    }

    /**
     * 清除所有数据
     */
    fun clear() {
        val sp = UiUtils.context.getSharedPreferences("bill", Context.MODE_PRIVATE)
        val editor = sp.edit()
        editor.clear()
        BillPreference.SharedPreferencesCompat.apply(editor)
    }

    /**
     * 查询某个key是否已经存在
     *
     * @param key
     * @return
     */
    operator fun contains(key: String): Boolean {
        val sp = UiUtils.context.getSharedPreferences("bill", Context.MODE_PRIVATE)
        return sp.contains(key)
    }

    /**
     * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类
     */
    private object SharedPreferencesCompat {
        private val sApplyMethod = findApplyMethod()

        /**
         * 反射查找apply的方法
         *
         * @return
         */
        private fun findApplyMethod(): Method? {
            try {
                val clz = SharedPreferences.Editor::class.java
                return clz.getMethod("apply")
            } catch (e: NoSuchMethodException) {

            }

            return null
        }

        /**
         * 如果找到则使用apply执行，否则使用commit
         *
         * @param editor
         */
        fun apply(editor: SharedPreferences.Editor) {
            try {
                if (sApplyMethod != null) {
                    sApplyMethod.invoke(editor)
                    return
                }
            } catch (e: IllegalArgumentException) {

            } catch (e: IllegalAccessException) {

            } catch (e: InvocationTargetException) {

            }

            editor.commit()
        }
    }

    /**
     * 存储List集合
     *
     * @param
     * @param key  存储的键
     * @param list 存储的集合
     */
    fun putList(key: String, list: List<Serializable>) {
        val sp = UiUtils.context.getSharedPreferences("bill", Context.MODE_PRIVATE)
        val editor = sp.edit()
        if (null == gson) {
            gson = Gson()
        }
        val data = gson!!.toJson(list)
        editor.putString(key, data)
        editor.apply()
    }

    /**
     * 获取List集合
     *
     * @param上下文
     * @param key     键
     * @return List集合
     */
    fun getList(key: String): List<String> {
        val sp = UiUtils.context.getSharedPreferences("bill", Context.MODE_PRIVATE)
        if (null == gson) {
            gson = Gson()
        }
        val data = sp.getString(key, "")
        //        Gson gson = new Gson();
        val listType = object : TypeToken<List<String>>() {

        }.type
        var list: List<String>? = gson!!.fromJson<List<String>>(data, listType)
        if (list == null) {
            list = ArrayList()
        }
        return list
    }

    fun getBeanList(key: String): List<Serializable>? {
        val sp = UiUtils.context.getSharedPreferences("bill", Context.MODE_PRIVATE)
        if (null == gson) {
            gson = Gson()
        }
        val data = sp.getString(key, "")
        //        Gson gson = new Gson();
        val listType = object : TypeToken<List<String>>() {

        }.type
        var list: List<*>? = gson!!.fromJson<List<*>>(data, listType)
        if (list == null) {
            list = ArrayList<Any>()
        }
        return list as List<Serializable>?
    }

}
